<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();

// 读取总价
const total_price = parseFloat(route.query.total || 0);

// Utility functions
const formatDate = (dateStr) => new Date(dateStr).toLocaleDateString('zh-CN');

const getCouponTypeText = (type) => {
    const types = {
        '0': '全场通用',
        '1': '指定科室',
        '2': '指定医生',
        '3': '指定医院'
    };
    return types[type] || '通用券';
};

const getDiscountText = (sale) => {
    if (sale.startsWith('*')) {
        return `${parseFloat(sale.slice(1)) * 10}折`;
    } else if (sale.startsWith('-')) {
        return `减${sale.slice(1)}元`;
    }
    return sale;
};

// API function
const fetchValidCoupons = async (doctorId) => {
    const response = await fetch('http://127.0.0.1:8000/coupon/enable/', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ doctor_id: doctorId })
    });

    if (!response.ok) {
        throw new Error('Failed to fetch coupons');
    }

    const data = await response.json();
    return data.coupon;
};

// Component logic
const coupons = ref([]);
const loading = ref(false);
const error = ref(null);

// 加载优惠券
const loadCoupons = async () => {
    const doctorId = localStorage.getItem('doctorId');
    if (!doctorId) {
        error.value = '未找到医生信息';
        return;
    }

    loading.value = true;
    error.value = null;

    try {
        coupons.value = await fetchValidCoupons(doctorId);
    } catch (e) {
        error.value = '获取优惠券失败';
        console.error(e);
    } finally {
        loading.value = false;
    }
};

// 选择优惠券
const handleCouponSelect = (coupon) => {
    if (total_price >= parseFloat(coupon.condition)) {
        localStorage.removeItem('selectedCoupon');
        localStorage.setItem('selectedCoupon', JSON.stringify(coupon));
        router.back(); // 返回到支付页面
    }
};

// 返回上一页
const goBack = () => {
    router.back();
};

onMounted(() => {
    loadCoupons();
});
</script>


<template>
    <div class="app">
        <!-- Header -->
        <header class="header">
            <button class="back-button" @click="goBack">返回</button>
            <h1>选择优惠券</h1>
        </header>
        <main>
            <div class="coupon-list">
                <!-- 加载中状态 -->
                <div v-if="loading" class="loading">
                    加载中...
                </div>
                <!-- 错误状态 -->
                <div v-else-if="error" class="error-state">
                    {{ error }}
                </div>
                <!-- 空状态 -->
                <div v-else-if="coupons.length === 0" class="empty-state">
                    暂无可用优惠券
                </div>
                <!-- 优惠券列表 -->
                <div v-else class="coupon-grid">
                    <div v-for="coupon in coupons" :key="coupon.user_coupon_id" class="coupon-item"
                        :class="{ disabled: total_price < parseFloat(coupon.condition) }"
                        @click="handleCouponSelect(coupon)">
                        <div class="coupon-left">
                            <div class="amount">
                                <span class="value">{{ getDiscountText(coupon.sale) }}</span>
                            </div>
                            <div class="condition" v-if="coupon.condition">
                                满{{ coupon.condition }}可用
                            </div>
                        </div>
                        <div class="coupon-right">
                            <div class="type">{{ getCouponTypeText(coupon.coupon_type) }}</div>
                            <div class="validity">
                                有效期至: {{ formatDate(coupon.end_time) }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</template>


<style>
.app {
    max-width: 640px;
    margin: 0 auto;
    min-height: 100vh;
    background-color: #f8f9fa;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header {
    display: flex;
    align-items: center;
    background-color: #ffffff;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    border-bottom: 1px solid #ebebeb;
}

.header h1 {
    flex: 1;
    font-size: 18px;
    color: #333333;
    margin: 0;
    font-weight: 600;
    text-align: center;
}

.back-button {
    background: none;
    border: none;
    font-size: 16px;
    color: #00b578;
    cursor: pointer;
}

.loading,
.empty-state,
.error-state {
    text-align: center;
    padding: 32px;
    color: #888888;
    font-size: 14px;
}

.error-state {
    color: #e64545;
}

.coupon-grid {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.coupon-item {
    display: flex;
    background: #ffffff;
    border-radius: 12px;
    overflow: hidden;
    height: 96px;
    cursor: pointer;
    position: relative;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: opacity 0.2s ease, box-shadow 0.2s ease;
}

.coupon-item.disabled {
    opacity: 0.5;
    pointer-events: none;
}

.coupon-left {
    width: 96px;
    background: #00b38a;
    color: #ffffff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 12px;
}

.amount {
    font-size: 22px;
    font-weight: bold;
}

.condition {
    font-size: 12px;
    margin-top: 4px;
}

.coupon-right {
    flex: 1;
    padding: 16px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.type {
    font-size: 14px;
    font-weight: 600;
    color: #333333;
    margin-bottom: 8px;
}

.validity {
    font-size: 12px;
    color: #888888;
}


</style>